<template>
  <a-upload
    :data="dataObj"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="true"
    action="https://yixianfeng.oss-cn-beijing.aliyuncs.com/"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <img v-if="value" :src="value" alt="avatar" style="width: 100%;" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">
        Upload
      </div>
    </div>
  </a-upload>
</template>
<script>
  import { policy } from '@/utils/oss'

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  export default {
    props: {
      value: String,
    },
    data() {
      return {
        loading: false,
        previewVisible: false,
        previewImage: '',
        dataObj: {
          imageUrl: '',
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: 'https://yixianfeng.oss-cn-beijing.aliyuncs.com/'
        },
      };
    },
    methods: {
      handleChange(info) {

        if (info.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl => {
            this.imageUrl = imageUrl;
            this.loading = false;
          });
          //调用上传成功返回名称和路径
          let url = this.dataObj.host + '/' + this.dataObj.dir + '/' + info.file.uid + info.file.name.replace(/,/g, '')
          let audioElement = new Audio(url);
          let duration;
          let that = this;
          audioElement.addEventListener("loadedmetadata", function (_event) {
            duration = audioElement.duration; //时长为秒，小数，182.36
            that.$emit('child-event',duration);
          });
          this.$emit('change', url);
        }
      },
      beforeUpload(file) {
        let _self = this
        // 最大只能上传10M文件
        // if (file.size > 10485760) {
        //   this.$message.error('上传失败，最大只能上传10M大小的图片')
        //   return false
        // }
        return new Promise((resolve, reject) => {
          policy().then(response => {
            _self.dataObj.policy = response.result.policy
            _self.dataObj.signature = response.result.signature
            _self.dataObj.ossaccessKeyId = response.result.accessKeyId
            _self.dataObj.key = response.result.dir + '/' + file.uid + file.name.replace(/,/g, '')
            _self.dataObj.dir = response.result.dir
            _self.dataObj.host = this.dataObj.host
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      handlePreview(file){
        if(this.fileType === FILE_TYPE_IMG){
          this.previewImage = file.url || file.imageUrl;
          this.previewVisible = true;
        }else{
          location.href=file.url
        }
      },
    },
  };
</script>
<style>
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
